package sd.czw.com.mmgapp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.snappingstepper.SnappingStepper;
import com.bigkoo.snappingstepper.listener.SnappingStepperValueChangeListener;
import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import sd.czw.com.mmgapp.Contants;
import sd.czw.com.mmgapp.R;
import sd.czw.com.mmgapp.adapter.GoodsDetatilsAdapter;
import sd.czw.com.mmgapp.adapter.ShopSpecAdapter;
import sd.czw.com.mmgapp.fragment.GoodsDetailFragmentLeft;
import sd.czw.com.mmgapp.fragment.GoodsDetailFragmentRight;
import sd.czw.com.mmgapp.mcallback.MyGoodsDetatilsCallback;
import sd.czw.com.mmgapp.model.goodsbean.GoodsdetailleftModel;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalCallback;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalModel;
import sd.czw.com.mmgapp.utils.SpUtils;

/**
 * Created by czw
 * desc 描述：商品详情界面   此处继承fragmentactivity  避免应用程序默认是app的fragmentmanager
 */
public class GoodsDeatilActivity extends FragmentActivity {

    @Bind(R.id.goodsdetail_backimage)
    RelativeLayout goodsdetail_backimage;
    @Bind(R.id.tv_sc)
    TextView tvSc;//收藏
    @Bind(R.id.tv_cart)
    TextView tvCart;//购物车
    @Bind(R.id.tv_add_cart)
    TextView tvAddCart;//加入购物车
    @Bind(R.id.tv_gm)
    TextView tvGm;//立即购买
    @Bind(R.id.iv_sc)
    ImageView ivSc;
    @Bind(R.id.rl_sc)
    RelativeLayout rlSc;
    @Bind(R.id.iv_cart)
    ImageView ivCart;
    @Bind(R.id.rl_cart)
    RelativeLayout rlCart;
    @Bind(R.id.tv_bg)
    TextView tv_bg;
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private List<GoodsdetailleftModel.ErrmsgBean.GoodsBean.SpecificationBean> speclist = new ArrayList<>();
    private Map<Integer, Integer> map = new TreeMap<>();
    private List<String> idlist = new ArrayList<>();
    private TabLayout mTab;
    private ViewPager viewPager;
    private String goods_id;
    private String token;
    private String username;
    private int is_collect;
    private GoodsdetailleftModel model;
    private PopupWindow popupWindow;
    private String shop_price;
    private String goods_number;
    private String goods_img;
    private ShopSpecAdapter shopSpecAdapter;
    private boolean isaddcart;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodsdetails);
        ButterKnife.bind(this);
        goods_id = getIntent().getStringExtra("goods_id");
        token = SpUtils.setToken(this).getString("token", "");
        username = SpUtils.setUsername(this).getString("username", "");
        model = new GoodsdetailleftModel();
        System.out.println("goods_id=" + goods_id);
        System.out.println("time=" + Contants.Time);
        System.out.println("token=" + token);
        System.out.println("sign=" + Contants.Sign);
        System.out.println("username=" + username);
        //准备数据
        initdatas();
        //获取控件
        initviews();
        //设置viewpager  tablayout
        setWithTabVp();
    }


//    @Override
//    protected void onRestart() {
//        super.onRestart();
////        token = SpUtils.setToken(this).getString("token", "");
////        username = SpUtils.setUsername(this).getString("username", "");
////        initdatas();
//    }

    @OnClick({R.id.goodsdetail_backimage,R.id.rl_sc, R.id.rl_cart, R.id.tv_add_cart, R.id.tv_gm})
    void onclick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.goodsdetail_backimage:
                onBackPressed();
                break;
            //收藏
            case R.id.rl_sc:
                token = SpUtils.setToken(this).getString("token", "");
                username = SpUtils.setUsername(this).getString("username", "");
                if (token == null ||("".equals(token))) {
                    startActivity(new Intent(this, LoginActivity.class));
                    //overridePendingTransition(R.anim.push_bottom_out1,R.anim.push_bottom_in1);
                }else {
                    if (is_collect == 0) {
                        OkHttpUtils.post().url(Contants.TG_URL).addParams("username", username)
                                .addParams("token", token)
                                .addParams("time", Contants.Time)
                                .addParams("sign", Contants.Sign)
                                .addParams("act", "add_collection")
                                .addParams("goods_id", goods_id)
                                .build().execute(new LoginNormalCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(LoginNormalModel response, int id) {
                                if (response.getErrcode() == 1) {
                                    Toast.makeText(GoodsDeatilActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                    tvSc.setTextColor(ContextCompat.getColor(GoodsDeatilActivity.this,R.color.m_titles));
                                    ivSc.setImageDrawable(ContextCompat.getDrawable(GoodsDeatilActivity.this,R.drawable.shoucang_collect));
                                    is_collect = 1;
                                } else {
                                    Toast.makeText(GoodsDeatilActivity.this, "" + response.getErrmsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }else if (is_collect == 1){
                        OkHttpUtils.post().url(Contants.TG_URL).addParams("username", username)
                                .addParams("token", token)
                                .addParams("time", Contants.Time)
                                .addParams("sign", Contants.Sign)
                                .addParams("act", "add_collection")
                                .addParams("goods_id", goods_id)
                                .build().execute(new LoginNormalCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(LoginNormalModel response, int id) {
                                if (response.getErrcode() == 1) {
                                    Toast.makeText(GoodsDeatilActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                                    tvSc.setTextColor(ContextCompat.getColor(GoodsDeatilActivity.this,R.color.shoucang));
                                    ivSc.setImageDrawable(ContextCompat.getDrawable(GoodsDeatilActivity.this,R.drawable.small_shoucang));
                                    is_collect = 0;
                                } else {
                                    Toast.makeText(GoodsDeatilActivity.this, "" + response.getErrmsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                }
                break;
            //购物车
            case R.id.rl_cart:
                token = SpUtils.setToken(this).getString("token", "");
                username = SpUtils.setUsername(this).getString("username", "");
                if (token != null && !("".equals(token))){
                    startActivity(new Intent(this,ShopCartActivity.class));
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
            //加入购物车
            case R.id.tv_add_cart:
                token = SpUtils.setToken(this).getString("token", "");
                username = SpUtils.setUsername(this).getString("username", "");
                isaddcart = true;
                if (token != null && !("".equals(token))){
                    addShopCart();
                }else{
                    startActivity(new Intent(GoodsDeatilActivity.this, LoginActivity.class));
                }
                break;
            case R.id.tv_gm://立即购买
                token = SpUtils.setToken(this).getString("token", "");
                username = SpUtils.setUsername(this).getString("username", "");
                isaddcart = false;
                if (token != null && !("".equals(token))) {
                    addShopCart();
                }else {
                    startActivity(new Intent(this,LoginActivity.class));
                }
                break;
        }
    }

    private void addShopCart() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.addcart_goods, null);
        popupWindow =  new PopupWindow(this);
        popupWindow.setContentView(inflate);
        popupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        //this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#00FFFFFF"));
        popupWindow.setBackgroundDrawable(dw);
        //显示窗口
        popupWindow.showAtLocation(findViewById(R.id.activity_goodsll), Gravity.BOTTOM| Gravity.CENTER_HORIZONTAL, 0, 0);

        if (popupWindow.isShowing()){
            tv_bg.setVisibility(View.VISIBLE);
        }else {
            tv_bg.setVisibility(View.GONE);
        }

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tv_bg.setVisibility(View.GONE);
            }
        });
        final JSONObject jsonObject = new JSONObject();
        TextView tv_price = (TextView) inflate.findViewById(R.id.tv_price);
        TextView tv_kc = (TextView) inflate.findViewById(R.id.tv_kc);
        ImageView imageView = (ImageView) inflate.findViewById(R.id.iv_goods);
        Glide.with(this).load(Contants.BASE_URL+goods_img).asBitmap().into(imageView);
        RecyclerView recyclerView = (RecyclerView) inflate.findViewById(R.id.rv);
        //开始商品规格
        if(speclist.size()>0){
            recyclerView.setVisibility(View.VISIBLE);
            LinearLayoutManager manager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(manager);
            shopSpecAdapter = new ShopSpecAdapter(GoodsDeatilActivity.this, speclist);
            recyclerView.setAdapter(shopSpecAdapter);
        }else {
            recyclerView.setVisibility(View.GONE);
        }
        Button btn_add = (Button) inflate.findViewById(R.id.btn_add_cart);
        tv_price.setText("¥"+shop_price);
        tv_kc.setText("库存"+goods_number);

        //商品数量加减按钮
        SnappingStepper stepper = (SnappingStepper) inflate.findViewById(R.id.stepper);
        stepper.setOnValueChangeListener(new SnappingStepperValueChangeListener() {
            @Override
            public void onValueChange(View view, int value) {
                try {
                        jsonObject.put("number",value);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }
        });
        int value = stepper.getValue();
        try {
            jsonObject.put("goods_id",goods_id);
            jsonObject.put("number",value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //加入购物车
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (speclist.size() > 0){
                    map.putAll(shopSpecAdapter.getMap());
                    for (Integer position : map.keySet()) {
                        idlist.add(speclist.get(position).getValues().get(map.get(position)).getId());
                    }
                }
            try {
                jsonObject.put("spec",new JSONArray(idlist));
            } catch (JSONException e) {
                e.printStackTrace();
            }
                    OkHttpUtils.post().url(Contants.ADD_CART).addParams("username",username)
                            .addParams("token",token)
                            .addParams("time",Contants.Time)
                            .addParams("sign",Contants.Sign)
                            .addParams("step","add_to_cart")
                            .addParams("goods",jsonObject.toString())
                            .build().execute(new LoginNormalCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(LoginNormalModel response, int id) {
                            if (response.getErrcode() == 1){
                                if (popupWindow.isShowing()){
                                    popupWindow.dismiss();
                                }
                                if (!isaddcart){
                                    startActivity(new Intent(GoodsDeatilActivity.this,ShopCartActivity.class));
                                }else {
                                    Toast.makeText(GoodsDeatilActivity.this, "商品添加购物车成功", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Toast.makeText(GoodsDeatilActivity.this, ""+response.getErrmsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            });
    }

    //准备数据
    private void initdatas() {
        fragments.add(GoodsDetailFragmentLeft.newInstance(goods_id));
        fragments.add(GoodsDetailFragmentRight.newInstance(goods_id));

        titles.add("商品");
        titles.add("详情");

        Map<String,String> params = new HashMap<>();
        if (token != null && !("").equals(token)){
            params.put("token",token);
        }
        if (username != null && !("".equals(username))){
            params.put("username",username);
        }
        params.put("time",Contants.Time);
        params.put("sign",Contants.Sign);
        params.put("id",goods_id);
        OkHttpUtils.post()
                .url(Contants.GOODS_DETATIL)
                .params(params).build().execute(new MyGoodsDetatilsCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(GoodsdetailleftModel response, int id) {
                Integer errcode = response.getErrcode();
                GoodsdetailleftModel.ErrmsgBean errmsg = response.getErrmsg();
                if (errcode == 1 && errcode != null) {
                    is_collect = errmsg.getIs_collect();
                    goods_number = errmsg.getGoods().getGoods_number();
                    shop_price = errmsg.getGoods().getShop_price();
                    goods_img = errmsg.getGoods().getGoods_img();
                    List<GoodsdetailleftModel.ErrmsgBean.GoodsBean.SpecificationBean> specification = errmsg.getGoods().getSpecification();
                    if (specification.size() > 0){
                        speclist.addAll(specification);
                    }
                    if (is_collect == 0) {
                        tvSc.setTextColor(ContextCompat.getColor(GoodsDeatilActivity.this,R.color.shoucang));
                        ivSc.setImageDrawable(ContextCompat.getDrawable(GoodsDeatilActivity.this,R.drawable.small_shoucang));
                    }else {
                        tvSc.setTextColor(ContextCompat.getColor(GoodsDeatilActivity.this,R.color.m_titles));
                        ivSc.setImageDrawable(ContextCompat.getDrawable(GoodsDeatilActivity.this,R.drawable.shoucang_collect));
                    }
                } else if (errcode != null && errcode == 1001) {
                    Toast.makeText(GoodsDeatilActivity.this, "请刷新重试", Toast.LENGTH_LONG).show();
                } else {
                    if (errmsg != null) {
                        Toast.makeText(GoodsDeatilActivity.this, errmsg.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    //获取控件
    private void initviews() {
        mTab = (TabLayout) findViewById(R.id.goodsdetatil_tab);
        viewPager = (ViewPager) findViewById(R.id.goodsdetatils_vp);
    }

    //设置viewpager  tablayout
    private void setWithTabVp() {
        for (int i = 0; i < titles.size(); i++) {
            mTab.addTab(mTab.newTab().setText(titles.get(i)));
        }
        GoodsDetatilsAdapter goodsDetatilsAdapter = new GoodsDetatilsAdapter(getSupportFragmentManager(), titles, fragments);
        goodsDetatilsAdapter.notifyDataSetChanged();
        viewPager.setAdapter(goodsDetatilsAdapter);
        mTab.setupWithViewPager(viewPager);
    }

}
